package com.example.exam.sysPermission.service;

import com.example.exam.common.ResultBean;
import com.example.exam.common.ResultBeanCodeEnum;
import com.example.exam.sysDictInfo.dao.SysDictInfoDao;
import com.example.exam.sysDictInfo.model.SysDictInfoBean;
import com.example.exam.sysPermission.dao.SysPermissionDao;
import com.example.exam.sysPermission.entity.SysPermissionBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
public class SysPermissionService {

	@Autowired
	private SysPermissionDao sysPermissionDao;
	@Autowired
	private SysDictInfoDao sysDictInfoDao;
	/**
	 * @Description:
	 * @Param: [resourceId]
	 * @return: java.util.List<com.example.exam.sysPermission.entity.SysPermissionBean>
	 * @Author: xhw
	 * @Date: 2021/7/26
	 */
	public List<SysPermissionBean> queryPermissionList(Integer resourceId) {
		return sysPermissionDao.queryPermissionList(resourceId);
	}
	/**
	 * @Description:
	 * @Param: [resourceId, ids, request]
	 * @return: com.example.exam.common.ResultBean
	 * @Author: xhw
	 * @Date: 2021/7/26
	 */
	public ResultBean savePermissionByResourceId(Integer resourceId, String ids, HttpServletRequest request) {
		ResultBean resultBean = new ResultBean();
		try {
			List<SysPermissionBean> listPermission = sysPermissionDao.queryPermissionList(resourceId);
			for (SysPermissionBean permission : listPermission) {
				sysPermissionDao.deletePer(permission.getId());
			}
			String[] permissionId = ids.split(",");
			if(permissionId.length>1){
				//int count=0;
				for (int i = 0;i< permissionId.length;i++) {
					SysDictInfoBean dictInfo = sysDictInfoDao.findById(Integer.parseInt(permissionId[i]));
					SysPermissionBean bean = new SysPermissionBean();
					bean.setCoding(dictInfo.getMark());
					bean.setName(dictInfo.getName());
					bean.setResourceId(resourceId);
					HttpSession session=request.getSession();
					Integer userId=(Integer)session.getAttribute("id");
					bean.setCreateUser(userId);
					bean.setState(1);
					bean.setCreateTime(new Date());
					sysPermissionDao.add(bean);
				}
			}
			resultBean.setCode(ResultBeanCodeEnum.OPERA_SUCCESS.getCode());
			resultBean.setMsg(ResultBeanCodeEnum.OPERA_SUCCESS.getMsg());
		} catch (NumberFormatException e) {
			e.printStackTrace();
			resultBean.setCode(ResultBeanCodeEnum.OPERA_EXCEPTION.getCode());
			resultBean.setMsg(ResultBeanCodeEnum.OPERA_EXCEPTION.getMsg());
		}
		return resultBean;
	}
}
